package com.twt.sys.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.twt.common.utils.Assert;
import com.twt.model.system.entity.SysDictItem;
import com.twt.sys.base.AbstractBaseService;
import com.twt.sys.mapper.SysDictItemMapper;
import com.twt.sys.service.SysDictItemService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SysDictItemServiceImpl extends AbstractBaseService<SysDictItemMapper, SysDictItem> implements SysDictItemService {

    @Override
    protected void beforeSave(SysDictItem sysDictItem) {
        Assert.isBlank(sysDictItem.getDictId(), "字典id不能为空！");
        Assert.isBlank(sysDictItem.getItemLabel(), "描述不能为空！");
        Assert.isBlank(sysDictItem.getItemValue(), "键值不能为空！");
    }

    public void add(SysDictItem addVo) {
        this.beforeSave(addVo);

        QueryWrapper<SysDictItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_id", addVo.getDictId());
        int count = this.count(queryWrapper);

        addVo.setSort(count + 1);
        addVo.setId(IdUtil.getSnowflakeNextIdStr());
        this.save(addVo);
    }

    public Page<SysDictItem> queryPageByQueryVo(Page<SysDictItem> page, SysDictItem po) {
        Assert.isBlank(po.getDictId(), "字典主键不能为空");
        LambdaQueryWrapper<SysDictItem> queryWrapper = Wrappers.lambdaQuery(new SysDictItem())
                .eq(SysDictItem::getDictId, po.getDictId())
                .orderByAsc(SysDictItem::getSort);
        return this.page(page, queryWrapper);
    }

    @Override
    public List<SysDictItem> queryByDictId(String dictId) {
        QueryWrapper<SysDictItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_id", dictId);
        return this.list(queryWrapper);
    }
}
